package com.jqb.hibernatebbs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.jqb.hibernatebbs.util.SessionLazyHandler;
/**
 * openSessionInView方案(扩大Session存在范围)
 * @author Dong
 *
 */
public class SessionFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		Session session = null;
		Transaction transaction = null;
		try {
			//获得线程级Session
			session = SessionLazyHandler.getCurrentSession();
			//开启事务
			transaction = session.beginTransaction();
			//放行
			chain.doFilter(request, response);
			//请求返回后提交事务
			transaction.commit();
			
		} catch (Exception e) {
			e.printStackTrace();
			if(transaction!=null){
				transaction.rollback();
			}
			throw new RuntimeException(e.getMessage());
		}finally{
			SessionLazyHandler.closeCurrentSession();
		}
	}

	@Override
	public void destroy() {
		
	}

}
